import React, { Component } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Card, message, Button, Popconfirm } from 'antd';
import { connect } from 'dva';
import Ellipsis from '../../../components/Ellipsis';
import { filterAuth } from '@/support/common';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoModalForm from '../../../components/common/PateoModalForm';

const mapStateToProps = (state: any) => ({
  dict: state.dict,
  menu: state.menu,
  loading: state.loading.models['dict'],
});

class DataDictList extends Component<any, any> {
  state = {
    formValues: {},
    visible: false,
    postUrl: '',
    formData: {},
    pageLoading: false,
    selectedRowKeys: [],
    refreshLoading: false
  };

  componentDidMount() {
    this.handleRefresh();
  }

  handleRefresh = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'dict/postFetchPage',
      payload: { url: '/dict/page' },
    });
    this.setState({
      selectedRowKeys: [],
    })
  };

  handleNotice = () => {
    message.success('操作成功！');
    this.handleRefresh();
  };

  handleDelete = (sid: any) => {
    const { dispatch } = this.props;
    const dict = [];
    dict.push(sid);
    dispatch({
      type: 'dict/postObjWithRes',
      payload: { url: `/dict/del`, dictList: dict },
      callback: (response: any) => this.handleNotice(),
    });
  };

  handleAdd = () => {
    this.setState({
      visible: true,
      postUrl: '/dict/add',
    });
  };

  handleEdit = (record: any) => {
    this.setState({
      formData: record,
      visible: true,
      postUrl: '/dict/edit',
    });
  };

  handleFlushPage = (flag = undefined) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'dict/postFetchPage',
      payload: { url: '/dict/page', ...formValues },
    });
    this.setState({
      selectedRowKeys: [],
    })
  };

  setPageLoading = (value: any) => {
    this.setState({
      pageLoading: value,
    });
  }

  handleBatchDelete = (key: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'dict/postObjWithRes',
      payload: { url: `/dict/del`, dictList: key },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('删除成功！');
          this.setState({ selectedRowKeys: [] });
          this.handleFlushPage();
        }
      },
    });
  };

  handleRefreshRedis = () => {
    this.setState({
      refreshLoading: true,
    })
    const { dispatch } = this.props;
    dispatch({
      type: 'dict/getDataWithRes',
      payload: { url: `/dict/cacheredis` },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('操作成功！');
          this.setState({
            refreshLoading: false,
          })
        } else {
          this.setState({
            refreshLoading: false,
          })
        }
      },
    });
  }

  render() {
    const { dict: { pageData: { list, pagination } }, loading, menu: { permissions }, location: { pathname } } = this.props;
    const { formValues, visible, postUrl, formData, selectedRowKeys, refreshLoading } = this.state;

    const columns = [
      {
        title: '编码',
        dataIndex: 'dictCode',
        render: (text: any) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: 'key',
        dataIndex: 'dictKey',
        width: '8%',
        render: (text: any) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        )
      },
      {
        title: 'value',
        dataIndex: 'dictValue',
        render: (text: any) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        )
      },
      {
        title: '描述',
        dataIndex: 'dictDesc',
        render: (text: any) => (
          <Ellipsis length={12} tooltip>
            {text}
          </Ellipsis>
        )
      },
      {
        title: '排序',
        dataIndex: 'dictSort',
        width: '6%',
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 150,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: "dict_doEdit",
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: '删除',
              key: 'del',
              auth: "dict_doDel",
              message: '是否确认删除？',
              Popconfirm: true,
              onConfirm: () => this.handleDelete(record.sid),
            }
          ];
          return <PateoAuthButtons btns={btns} max={1} pathname={pathname} />;
        },
      },
    ];
    const searchItems = [
      {
        type: 'input',
        title: '编码',
        key: 'dictCode',
      },
      {
        type: 'input',
        title: 'key',
        key: 'dictKey',
      },
      {
        type: 'input',
        title: 'value',
        key: 'dictValue',
      },
      {
        type: 'input',
        title: '描述',
        key: 'dictDesc',
      }
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys: any) => {
        this.setState({ selectedRowKeys });
      },
    };
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.sid,
      pagination: paginationProps,
      rowSelection,
      selectedRows: selectedRowKeys
    };
    const formItems = [
      {
        type: 'input',
        title: '编码',
        key: 'dictCode',
        editDisabled: true,
        rules: [{ required: true, message: '请输入编码！', whitespace: true, max: 50 }],
        maxLength: 50,
      },
      {
        type: 'input',
        title: 'key',
        key: 'dictKey',
        rules: [{ required: true, message: '请输入key！', whitespace: true, max: 50 }],
        maxLength: 50,
      },
      {
        type: 'input',
        title: 'value',
        key: 'dictValue',
        rules: [{ required: true, message: '请输入value！', whitespace: true, max: 4000 }],
        maxLength: 4000,
      },
      {
        type: 'textArea',
        title: '描述',
        key: 'dictDesc',
        rules: [{ required: false, message: '请输入描述！', max: 200 }],
        maxLength: 200,
      },
      {
        type: 'inputNumber',
        title: '排序',
        key: 'dictSort',
        min: 1,
        rules: [{ required: false, message: '请输入排序！' }],
      },
    ];
    return (
      <div>
        <Card title="" bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{ type: 'dict/postFetchPage', url: '/dict/page' }}
            saveFormValues={val => this.setState({ formValues: Object.assign(formValues, val), selectedRowKeys: [] })}
            handleFormReset={() => this.setState({ formValues: {}, selectedRowKeys: [] })}
          />
        </Card>
        <Card bordered={false} style={{ marginTop: 12 }}>
          <div className="my_newItem">
            {
              filterAuth("dict_doDel", permissions, pathname) && selectedRowKeys.length > 0 &&
              <span>
                <Popconfirm
                  title="是否确认删除所选数据字典？"
                  onConfirm={() => this.handleBatchDelete(selectedRowKeys)}
                >
                  <Button
                    style={{ float: 'left' }}
                    type="danger"
                    htmlType="submit"
                    size="small"
                  >
                    批量删除
                  </Button>
                </Popconfirm>
                <span style={{ float: 'left' }}>已选&nbsp;{selectedRowKeys.length}&nbsp;项&nbsp;&nbsp;&nbsp;&nbsp;</span>
              </span>
            }
            {filterAuth("dict_doAdd", permissions, pathname) &&
              <Button onClick={() => this.handleAdd()} size="small" icon={<PlusOutlined />} type="primary">新增</Button>
            }
            &nbsp;&nbsp;
            {
              filterAuth("dict_doCacheRedis", permissions, pathname) &&
              <Popconfirm
                title="是否确认刷新缓存？"
                onConfirm={() => this.handleRefreshRedis()}
                placement="topRight"
              >
                <Button loading={refreshLoading} size="small" type="primary">刷新缓存</Button>
              </Popconfirm>
            }
          </div>
          <PateoTable
            extraHandle={true}
            formValues={formValues}
            tableProps={tableProps}
            fetchParams={{ type: 'dict/postFetchPage', url: '/dict/page' }}
          />
        </Card>
        <PateoModalForm
          style={{ top: 50 }}
          formItems={formItems}
          changeVisible={() => this.setState({ formData: {}, visible: false, postUrl: '' })}
          formData={formData}
          visible={visible}
          postUrl={postUrl}
          handleCallback={this.handleFlushPage}
          title={["新增数据字典", "编辑数据字典"]}
          messageInfo={["新增成功", "编辑成功"]}
          buttonName={["保存", "取消"]}
        />
      </div>
    );
  }
}

export default connect(mapStateToProps)(DataDictList);
